package com.platform.cdcs.fragment.custom;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.PriceItem;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.trueway.app.uilib.activity.BaseActivity;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.sql.Ref;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * Created by holytang on 2017/12/27.
 */
public class AddPriceFragment extends BaseFragment {

    private EditText priceET, unit2ET;
    private TextView unitTV;
    private String[] unitArray;

    @Override
    public void initView(View view) {
        setTitle("新价格");
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        initLoadImg(view.findViewById(R.id.load));
        TextView cancelBtn = (TextView) view.findViewById(R.id.button1);
        cancelBtn.setText("取消");
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                priceET.setText("");
                unit2ET.setText("");
                unitTV.setText("");
            }
        });
        TextView okBtn = (TextView) view.findViewById(R.id.button2);
        okBtn.setText("确定");
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                post();
            }
        });

        priceET = (EditText) view.findViewById(R.id.title);
        unitTV = (TextView) view.findViewById(R.id.title1);
        view.findViewById(R.id.title2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUnit();
            }
        });
        unit2ET = (EditText) view.findViewById(R.id.title3);

    }

    @Override
    public int layoutId() {
        return R.layout.add_price;
    }

    private void post() {
        if (TextUtils.isEmpty(priceET.getText().toString().trim())) {
            Utils.showToast(getContext(), "价格不能为空!");
            return;
        }
        if (TextUtils.isEmpty(unitTV.getText().toString().trim())) {
            Utils.showToast(getContext(), "单位不能为空!");
            return;
        }
        if (TextUtils.isEmpty(unit2ET.getText().toString().trim())) {
            Utils.showToast(getContext(), "最小单位不能为空!");
            return;
        }
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("itemCode", getArguments().getString("itemCode"));
        map.put("cusCode", getArguments().getString("cusCode"));
        map.put("inUom", unitTV.getText().toString());
        map.put("price", priceET.getText().toString());
        map.put("rate", unit2ET.getText().toString());
        getHttpClient().post().url(Constant.ADD_INVOICE_PRICE).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                    }.getType();
                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        PriceItem item = new PriceItem();
                        item.setInUom(unitTV.getText().toString());
                        item.setPrice(priceET.getText().toString());
                        item.setUomPrice(unit2ET.getText().toString());
                        Bundle bundle = new Bundle();
                        RefershEvent event = new RefershEvent();
                        bundle.putSerializable("price", item);
                        event.bundle = bundle;
                        event.mclass = PriceListFragment.class;
                        EventBus.getDefault().post(event);
                        event = new RefershEvent();
                        bundle.putSerializable("price", item);
                        event.bundle = bundle;
                        event.mclass = EditPriceNumFragment.class;
                        EventBus.getDefault().post(event);
                        getActivity().finish();
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private void requestUnit() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "3");
        map.put("itemCode", getArguments().getString("itemCode"));
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        JSONArray jsonArray = obj.getJSONArray("uomList");
                        unitArray = new String[jsonArray.length()];
                        for (int j = 0; j < jsonArray.length(); j++) {
                            if (!TextUtils.isEmpty(jsonArray.getJSONObject(j).getString("uomName"))) {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " (" + jsonArray.getJSONObject(j).getString("uomName") + ")";
                            } else {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " ";
                            }
                        }
                        showUnit();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                    unitArray = null;
                }
            }
        });
    }

    private void showUnit() {
        if (unitArray == null) {
            requestUnit();
        } else {
            new TwDialogBuilder(getContext()).setItems("选择单位", unitArray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    unitTV.setText(unitArray[i]);
                    unitTV.setTag(unitArray[i].split(" ")[0]);
                }
            }).create().show();
        }
    }

}
